import api from "../../../api/index";
import { Message  } from 'element-ui';
export default {
  state:{
    loading:true,
    tableData:[]
  },
  getters:{
    kpi_monthOwnData:state=>{
      const now = new Date();
      return state.tableData.filter(item=>{
        const smonth = now.getMonth()+1>9?now.getMonth()+1:'0'+(now.getMonth()+1);
        return item.date.split("-")[0]==now.getFullYear()&&item.date.split("-")[1]==smonth;
      });
    }
  },

  mutations:{
    kpi_tableData(state,data){
      state.tableData=data;
    },
    kpi_showLoading(state){
      state.loading = true;
    },
    kpi_endLoading(state){
      state.loading = false;
    }
  },
  actions:{
    kpi_setTableData(context,params){
      //显示loading
      context.commit('kpi_showLoading');
      //发送ajax请求游戏数据
      return new Promise((resolve,reject) =>{
        api.setApi(params)
          .then((response) =>{
            Message({
              message: response.data.message,
              center: true,
              type:response.data.result?'success':'error'
            });
            resolve();
            context.commit('kpi_endLoading');

          })
          .catch((error)=> {
            reject();
            console.log(error);
          });
      } );

    },
    kpi_updateData(context,params){
      //显示loading
      context.commit('kpi_showLoading');
      //发送ajax请求游戏数据
      return new Promise((resolve,reject) =>{
        api.updateApi(params)
          .then((response) =>{
            Message({
              message: response.data.message,
              center: true,
              type:response.data.result?'success':'error'
            });
            resolve();
            context.commit('kpi_endLoading');

          })
          .catch((error)=> {
            reject();
            console.log(error);
          });
      } );

    },
    kpi_delData(context,params){
      //显示loading
      context.commit('kpi_showLoading');
      //发送ajax请求游戏数据
      return new Promise((resolve,reject) =>{
        api.delApi(params)
          .then((response) =>{
            Message({
              message: response.data.message,
              center: true,
              type:response.data.result?'success':'error'
            });
            resolve();
            context.commit('kpi_endLoading');
          })
          .catch((error)=> {
            reject();
            console.log(error);
          });
      } );

    },
    kpi_getTableData(context,params){
      //显示loading
      context.commit('kpi_showLoading');
      //发送ajax请求游戏数据
      api.getApi(params)
        .then((response) =>{
          let data = response.data.object;
          //判断数据是否正确
          if(data && Array.isArray(data)){
            context.commit('kpi_tableData',data);
          }
          context.commit('kpi_endLoading');
        })
        .catch((error)=> {
          console.log(error);
        });

    }
  }
}
